package com.tyun.modules.api.resolver;

import com.sun.org.apache.xpath.internal.operations.String;
import com.tyun.modules.api.annotation.LoginUser;
import com.tyun.modules.api.interceptor.AuthorizationInterceptor;
import com.tyun.modules.sys.entity.SysUser;
import com.tyun.modules.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数,注入当前登录用户
 *      自定义参数解析器,supportsParameter用于判断是否需要处理该参数分解,返回true为需要，并会去调用下面的方法resolveArgument
 *                     resolveArgument：真正用于处理参数分解的方法，返回的Object就是controller方法上的形参对象
 *
 * @author tao cong cong
 * @create 2018/2/17 下午4:42
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver{

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(LoginUser.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        Object object = request.getAttribute(AuthorizationInterceptor.LOGIN_USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (object == null) {
            return null;
        }
        String userId = (String)object;
        SysUser sysUser = sysUserService.selectById(userId);
        return sysUser;
    }
}
